package com.server.modules.api.service.impl;

import com.alibaba.fastjson.JSON;
import com.server.common.utils.HttpUtils;
import com.server.common.utils.PathUtils;
import com.server.modules.api.dao.MemberAPIDao;
import com.server.modules.api.service.WXService;
import com.server.modules.sys.entity.member.Member;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Properties;

/**
 * @Author SilentWolf
 * @Date 2016/8/4 14:08
 */

@Service
public class WXServiceImpl implements WXService {
	@Resource
	MemberAPIDao memberAPIDao;

	@Override
	public Member getUserInfo(String accessToken, String openId) throws Exception {
		String uri = "sns/userinfo?access_token=" + accessToken + "&openid=" + openId;
		String result = HttpUtils.sendGet(WX_URL + uri, "");
		Map userInfo = JSON.parseObject(result);

		Member member = null;
		if (userInfo.get("errcode") == null) {
			member = new Member();
			member.setSex(((Integer) userInfo.get("sex")) == 1 ? "男" : "女");
			member.setNickname((String) userInfo.get("nickname"));
//			member.setNativeProvince((String) userInfo.get("province"));
//			member.setResidentProvince((String) userInfo.get("province"));
//			member.setNativeCity((String) userInfo.get("city"));
//			member.setResidentCity((String) userInfo.get("city"));
			member.setUnionId((String) userInfo.get("unionid"));
			member.setOpenId((String) userInfo.get("unionid"));
			String imgUrl = HttpUtils.downLoadImage((String) userInfo.get("headimgurl"));

			Properties props = PathUtils.getProperties("application.properties");
			String imagePath = props.getProperty("imagePath");
			member.setFace(imagePath + imgUrl);
		} else {
			throw new Exception("用户信息获取错误");
		}
		return member;
	}

	@Override
	public boolean checkToken(String accessToken, String openId) {
/*		String uri = "sns/auth?access_token=" + accessToken + "&openid=" + openId;
		String result = HttpUtils.sendGet(WX_URL + uri, "");
		Map resultMap = JSON.parseObject(result);
		if ((Integer) resultMap.get("errcode") == 0) {
			return true;
		}
		return false;
	}*/
/*		String uri = "sns/userinfo?access_token=" + accessToken + "&openid=" + openId;
		String result = HttpUtils.sendGet(WX_URL + uri, "");
		Map userInfo = JSON.parseObject(result);

		Member member = null;
		if (userInfo.get("errcode") == null) {
			return true;
		}else return false;*/
		Member member = new Member();
		member.setAccessToken(accessToken);
		member.setUnionId(openId);
		Member result = memberAPIDao.loginByWx(member);
		if (result!= null){
			return true;
		}else return false;
	}
}
